<template>
    <nav-cus  @back="handleNavBack">
    <block v-if="!isNotCamera">
      <nav-tips />
    </block>
    <auth-toast :isShow="show_auth_panel" :authInfo="authInfo" />
    <error-toast :isShow="showErrorMsg" :err="err"/>
    <block v-if="livingbody.isShowGuide && !livingbody.isShowCamera">
      <view id="livingbody-guide-title">实名核身验证流程</view>
      <view class="livingbody-guide-imgview" v-if="cmsConfig.livingbodyType === 0">
        <image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/hint-heshen-number.png" />
      </view>
      <view class="livingbody-guide-imgview" v-else-if="cmsConfig.livingbodyType === 1">
        <image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/hint-heshen-action.png" />
      </view>
      <view class="livingbody-guide-imgview" v-else>
        <image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/hint-heshen-silent.png" />
      </view>
      <!-- next btn -->
      <view class="index-btn" id="livingbody-guide-btnview">
        <button type="primary" @click="livingbodyStartToRecord" hover-class='btn-hover' :disabled='livingbody.isNotPrepareOk'>
          开始识别
        </button>
      </view>
      <view id="livingbody-guide-showdialog">
        <text @click="switchLivingbodyDialog" style="padding:5px 10px">查看规范</text>
      </view>
      <risk-tips v-if="cmsConfig.Common.RiskTip"/>
    </block>
    
    <view   :style="{position:'absolute',top:0,bottom:0,width:'100%',left:livingbody.isShowCamera ? '0' : '100%'}">
      <!-- 读书模式 -->
      <camera device-position="front" flash="off" @error="ocrCameraError"  @stop="bindstop" class="livingbody-camera" :style="cmsConfig.livingbodyType === 0 ? {position:'absolute',top:0,bottom:0,width:'100%'} : ''">
        <block v-if="cmsConfig.livingbodyType === 0">
          <!-- livingbody title -->
        <cover-view  :class="['livingbody-title',livingbody.isInfinityDisplayHTTitle]">
          <risk-tips v-if="cmsConfig.Common.RiskTip"/>
          <cover-view class="livingbodyTitle">{{livingbody.livingbodyTitle}}</cover-view>
        </cover-view>
        <!-- livingbody bg -->
        <cover-image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/faceyzbg.png"  :class="['livingbody-bg',livingbody.isInfinityDisplayHTBottom]"></cover-image>
        <!-- livingbody number -->
        <cover-view  :class="['livingbody-number-pre',livingbody.isInfinityDisplayHTNumberPre]" v-if="livingbody.isPrepare">
          准备读数...
        </cover-view>
        <cover-view  :class="['livingbody-number-hint',livingbody.isInfinityDisplayHTNumberHint]" v-else>
            <cover-view v-for='i in 4' :key="i" :class="['lvingbody-number-text',livingbody.curNumberStatus[i]]">
              {{livingbody.livingbodyNumber[i]}}
            </cover-view>
        </cover-view>
        </block>
        <block v-if="cmsConfig.livingbodyType === 1">
          <!-- livingbody title -->
          <cover-view :class="['livingbody-title',livingbody.isInfinityDisplayHTTitle]">
            <risk-tips v-if="cmsConfig.Common.RiskTip" />
            <cover-view>{{livingbody.livingbodyTitle}}</cover-view>
          </cover-view>
          <!-- livingbody bg -->
          <cover-image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/faceyzbg.png" :class="['livingbody-bg',livingbody.isInfinityDisplayHTBottom]"></cover-image>
          <!-- livingbody action -->
          <cover-view :class="['livingbody-action-pre',livingbody.isInfinityDisplayHTActionPre]" v-if="livingbody.isPrepare">
            准备做动作...
          </cover-view>
          <cover-view :class="['livingbody-action-hint',livingbody.isInfinityDisplayHTActionHint]" v-else>
            {{livingbody.livingbodyActionText}}
          </cover-view>
        </block>
        <block v-else>
          <!-- livingbody title -->
        <cover-view  :class="['livingbody-title',livingbody.isInfinityDisplayHTTitle]">
          <risk-tips v-if="cmsConfig.Common.RiskTip"  />
          <cover-view>{{livingbody.livingbodyTitle}}</cover-view>
        </cover-view>
        <!-- livingbody bg -->
        <cover-image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/faceyzbg.png"  :class="['livingbody-bg',livingbody.isInfinityDisplayHTBottom]"></cover-image>
        <!-- livingbody silent -->
        <cover-view class="livingbody-silent">
          <cover-view class='livingbody-silent-view'>
            <cover-view class="livingbody-silent-prepare" v-if="livingbody.isPrepare">
              准备录制
            </cover-view>
            <cover-view class="livingbody-silent-hintone" v-if="!livingbody.isPrepare">
              录制中
            </cover-view>
            <cover-view class="livingbody-silent-hinttwo" v-if="!livingbody.isPrepare">
              {{livingbody.livingbodySilentText}}
            </cover-view>
          </cover-view>
        </cover-view>
        </block>
      </camera>
    </view>
    <view v-if="livingbody.isShowProcess && !livingbody.isShowGuide && !livingbody.isShowCamera" id="livingbody-process">
      <view class="scan">
        <image src="https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/loadding-white.gif" />
      </view>
      <view id="livingbody-process-m">
        <progress :percent="livingbody.uploadProcess" color="#2473e9" backgroundColor="#cbcbcb" stroke-width="6"></progress>
      </view>
      <view id="livingbody-process-title">系统识别中...</view>
      <risk-tips v-if="cmsConfig.Common.RiskTip"/>
    </view>
    <!-- dialog -->
    <view class="js_dialog" id="iosDialog1" style="opacity: 1" v-if="livingbody.isShowDialog">
      <!-- mask -->
      <view class="weui-mask"></view>
      <!-- main -->
      <view class="weui-dialog style3" id="livingbody-dialog-main">
        <!-- title -->
        <view class="weui-dialog__hd" id="livingbody-dialog-title">
          <strong class="weui-dialog__title">视频录制规范</strong>
        </view>
        <!-- bg and button -->
        <view class="weui-dialog__bd" id="livingbody-dialog-bg">
          <image src='https://faceid-verify-temp-1254418846.cos.ap-chengdu.myqcloud.com/images/v1videohint.png' />
          <view class="weui-btn_area">
            <button type="default" size="mini" plain="true" @click="switchLivingbodyDialog">
              我知道了
            </button>
          </view>
        </view>
      </view>
    </view>
    <!-- dialog -->
    <view v-if="livingbody.showTestVideo">
      <video id="myVideo" :src="livingbody.video_src" :poster="livingbody.video_preview" controls style="width:300px;height:300px;"></video>
    </view>
    </nav-cus>
</template>

<script>
import { sysFailInfo, tokenExceptionArr } from "../../utils/constant";
import riskTips from "../../components/riskTips/riskTips";
import navCus from "../../components/nav-cus/nav-cus";
import navTips from "../../components/navTips/navTips";
import authToast from "../../components/authToast/authToast";
import errorToast from "../../components/errorToast/errorToast";
import {
  startNativeVerify,
  exitVerify,
  exitVerifyFail,
  checkNetWork,
  checkRecordNetworkOk,
  eportError,
  Log,
  $common,
  $http,
  reportError
} from "../../utils";
const DefaultLivingbodyData = {
  isShowGuide: true,
  isShowCamera: false,
  isShowProcess: false,
  isShowDialog: false, // read number libingbody guide panel control
  livingbodyNumber: "",
  isNotPrepareOk: true, // guide page, is prepare not ok, enable or disable the start verify btn
  getCodeErrMsg: "",

  livingbodyTitle: "请保持正脸对准框内",
  isPrepare: true, // is prepare section
  curNumberStatus: ["verifyCurrentNumber", "", "", ""],
  curNumber: ["·", "·", "·", "·"],

  isActionSeqNormal: "", // 眨眨眼、张张嘴
  livingbodyActionText: "",

  livingbodySilentText: "",

  uploadProcess: 0,

  showTestVideo: false,
  video_preview: "",
  video_src: "",

  isInfinityDisplayHTTitle: "", // title
  isInfinityDisplayHTBottom: "", // bottom
  isInfinityDisplayHTMiddle: "", // middle
  isInfinityDisplayHTActionPre: "",
  isInfinityDisplayHTNumberPre: "",
  isInfinityDisplayHTActionHint: "",
  isInfinityDisplayHTNumberHint: ""
};
export default {
  components: {
    riskTips,
    navTips,
    authToast,
    errorToast,
    navCus
  },
  data() {
    return {
      show_auth_panel: false,
      authInfo: "",
      // livingbody
      livingbody: JSON.parse(JSON.stringify(DefaultLivingbodyData)),
      err: {
        error_msg: "",
        ErrorCode: -1
      },
      showErrorMsg: false,
      isNotCamera: false,
      ctx: null, // cameraCtx
      cmsConfig: uni.faceidVerifySdkCmsConfig,
      token: uni.faceidVerifySdkToken,
      baseUrl: uni.faceidVerifySdkBaseUrl,
      curPage: uni.faceidVerifySdkCurPage,
      isHide: false,
      readInterval: null
    };
  },
  onShow() {
    if (this.show_auth_panel) {
      // 加500ms延时，用iOS测试时，发现，设置后返回，onshow在执行检测时，刚才设置的权限还没有生效。导致检测到的还是原来的结果
      setTimeout(() => {
        this.isAuthOk();
      }, 500);
    }
    if (this.isHide) {
      this.handleHideStatus();
      this.$nextTick(() => {
        this.preLivingbodyExec();
      });
    }
  },
  onHide() {
    console.log("onHide");
    this.livingbody.isPrepare = true;
    this.livingbody.isShowGuide = true;
    this.livingbody.isShowCamera = false;
    this.isHide = true;
    clearInterval(this._interval);
  },
  onLoad(options) {
    console.log("verifyLivingBody onload", options);
    this.cmsConfig = uni.faceidVerifySdkCmsConfig;
    this.baseUrl = uni.faceidVerifySdkBaseUrl;
    this.token = uni.faceidVerifySdkToken;
    this.curPage = uni.faceidVerifySdkCurPage;
    this.livingbody = JSON.parse(JSON.stringify(DefaultLivingbodyData));
    this.$nextTick(() => {
      this.preLivingbodyExec();
    })
  },
  methods: {
    handleHideStatus() {
      this.isHide = false;
      this.showErrorToast({
        ErrorCode: -108,
        ErrorMsg: "startRecord timeoutCallback, 请重试！"
      });
      this.livingbody = JSON.parse(JSON.stringify(DefaultLivingbodyData));
      this.isNotCamera = false;
      this.ctx = null;
    },
    handleNavBack() {
      console.log('his.livingbody',this.livingbody)
      console.log('his.livingbody1',this.livingbody.isShowProcess &&
        !this.livingbody.isShowGuide &&
        !this.livingbody.isShowCamera
      )
      if (
        this.livingbody.isShowProcess &&
        !this.livingbody.isShowGuide &&
        !this.livingbody.isShowCamera
      )
        return;
      uni.navigateBack();
    },
    getAuth() {
      // 先授权，才能进行后续的逻辑
      wx.authorize({
        scope: "scope.camera",
        success: () => {},
        fail: () => {
          console.log("您未允许使用摄像头权限");
        },
        complete: () => {
          wx.authorize({
            scope: "scope.record",
            success: () => {},
            fail: () => {
              console.log("您未允许使用录音权限");
            },
            complete: () => {
              console.log("开始判断是否有权限");
              this.isAuthOk();
            }
          });
        }
      });
    },
    preLivingbodyExec() {
      console.log("cmsConfig", this.cmsConfig);
      // ocr 和 活体前置页面都是调用了授权
      // I need get the number when number livingbody, but the ocr has used this func too, So need some handle
      if (
        this.cmsConfig.livingbodyType === 0 ||
        this.cmsConfig.livingbodyType === 1
      ) {
        $http(
          {
            url:
              this.cmsConfig.livingbodyType === 1
                ? `/api/liveness/actioncode?BizToken=${this.token}`
                : `/api/liveness/lipcode?BizToken=${this.token}`,
            method: "POST",
            reTry: {
              tryCount: 5
            }
          },
          res => {
            if (res.ErrorCode === 0) {
              console.log("Got the LipCode：" + res.Data.LipCode);
              console.log("Got the ActionCode:" + res.Data.ActionCode);

              this.livingbody.livingbodyNumber = res.Data.LipCode;
              if (this.cmsConfig.livingbodyType === 1) {
                this.livingbody.isActionSeqNormal =
                  res.Data.ActionCode.join("") === "21";
              }
              this.getAuth();
            } else {
              // 如果出现 14(本次校验已完成) 15 (token过期)的错误，退出验证
              if (tokenExceptionArr.includes(res.ErrorCode)) {
                exitVerifyFail(res);
                return;
              }
              this.livingbody.getCodeErrMsg = res.ErrorMsg;
              this.getAuth();
              reportError(Log.preLivingbodyExecErr, res);
            }
          }
        );
      } else {
        this.getAuth();
      }
    },
    // check the auth is OK
    isAuthOk() {
      uni.getSetting({
        success: res => {
          console.log("获取授权信息成功");
          var isRecordAuthOk = res.authSetting["scope.record"];
          var isCameraAuthOk = res.authSetting["scope.camera"];
          if (isRecordAuthOk && isCameraAuthOk) {
            this.show_auth_panel = false;
            this.authInfo = "摄像头、录音功能都已授权";
            this.authOkToDo();
            console.log("摄像头、录音功能都已授权");
          } else {
            var errMsg = "";
            if (!isCameraAuthOk) {
              errMsg = "摄像头 ";
            }
            if (!isRecordAuthOk) {
              errMsg += "录音功能";
            }
            errMsg += "还未授权";
            console.log(errMsg);
            this.show_auth_panel = true;
            this.authInfo = errMsg;
          }
        },
        fail: e => {
          console.log("获取收取信息失败", e);
        }
      });
    },
    // auth ok, go to next logic
    authOkToDo() {
      console.log("authOkToDo", this.livingbody, this.cmsConfig.livingbodyType);
      if (
        (this.cmsConfig.livingbodyType === 0 &&
          this.livingbody.livingbodyNumber === "") ||
        (this.cmsConfig.livingbodyType === 1 &&
          this.livingbody.isActionSeqNormal === "")
      ) {
        this.theLivingBodyNumberMustBeOk();
      } else {
        this.livingbodyAutoShowDialog();
        this.livingbody.isNotPrepareOk = false;
      }
    },
    // 首次进入小程序必须看示范，已经查看过则点击展示
    livingbodyAutoShowDialog() {
      let isAlreadyShowVideoRule = uni.getStorageSync("isAlreadyShowVideoRule");
      console.log("isAlreadyShowVideoRule:" + isAlreadyShowVideoRule);
      // 如果有值，说明之前已经显示，有缓存，
      if (!isAlreadyShowVideoRule) {
        // 如果没有，说明第一次进入
        this.livingbody.isShowDialog = !this.livingbody.isShowDialog;
        uni.setStorage({
          key: "isAlreadyShowVideoRule",
          data: "true"
        });
      }
    },
    // livingbody start to record
    livingbodyStartToRecord() {
      checkNetWork(() => {
        this.livingbody.isShowCamera = true;
        this.isNotCamera = false;
        console.log("go", this.livingbody);
        this.$nextTick(() => {
          // after 2s, start record, 2s prepare,  准备读数.../准备做动作.../准备录制 stay 2s
          setTimeout(() => {
            // check the network again
            checkRecordNetworkOk(
              () => {
                // if that work ok
                console.log("start");

                this.ctx = uni.createCameraContext();
                console.log("start startRecord", this.ctx);
                this.ctx.startRecord({
                  success: res => {
                    console.log(
                      "startRecord success",
                      res,
                      this.cmsConfig.livingbodyType
                    );

                    let livingbodyType = this.cmsConfig.livingbodyType;
                    this.livingbody.isPrepare = false; // stop prepare
                    let count = 0;
                    let timeGap = 1200; // number livingbody read number gap, action livingbody 2000, silent livingbody 1000
                    let stopTimeGap = 1000; // number 1500, action 1000, livingbody 1000

                    // number livingbody, the var need used in the last flow
                    let numArr = this.livingbody.livingbodyNumber + "";

                    let silentCurNumber =
                      this.cmsConfig.page.livingbody.silentRecordTime - 1;

                    if (livingbodyType === 0) {
                      // startRecord status
                      this.livingbody.livingbodyTitle = "请大声朗读以下数字";
                      this.$set(
                        this.livingbody.curNumberStatus,
                        count,
                        "verifyCurrentNumber"
                      );
                      this.$set(
                        this.livingbody.curNumber,
                        count,
                        numArr[count]
                      );
                      stopTimeGap = 1500;
                    } else if (livingbodyType === 1) {
                      let isActionSeqNormal = this.livingbody.isActionSeqNormal;
                      // action
                      this.livingbody.livingbodyTitle = "请做以下动作";
                      this.livingbody.livingbodyActionText = isActionSeqNormal
                        ? "眨眨眼"
                        : "张张嘴";
                      timeGap = 2000;
                    } else {
                      // silent
                      this.livingbody.livingbodySilentText = silentCurNumber;
                      timeGap = 1000;
                    }

                    let _interval = setInterval(() => {
                      // nubmer livingbody  0  1.3s |  1  2.6s |  2 | 3.9s | 3  5.2s      1.2s *4 +stopgap 1.5s => 6.3s about 6s
                      if (livingbodyType === 0) {
                        if (count === 3) {
                          clearInterval(_interval);
                          this.stopRecordAndProcess(stopTimeGap);
                          return;
                        }
                        count++;
                        console.log("count", numArr, count, numArr[count]);
                        this.$set(
                          this.livingbody.curNumberStatus,
                          count,
                          "verifyCurrentNumber"
                        );
                        this.$set(
                          this.livingbody.curNumber,
                          count,
                          numArr[count]
                        );

                        console.log(
                          "this.livingbody.curNumber",
                          this.livingbody.curNumber
                        );
                      }

                      // action livingbody   2s *2 +stopgap 1s => 5s
                      else if (livingbodyType === 1) {
                        if (count === 1) {
                          clearInterval(_interval);
                          this.stopRecordAndProcess(stopTimeGap);
                          return;
                        }
                        count++;
                        this.livingbody.livingbodyActionText = this.livingbody
                          .isActionSeqNormal
                          ? "张张嘴"
                          : "眨眨眼";
                      }
                      // silent livingbody  1s * setTime +stopgap 1s => setTIme default 4s, about 5s+
                      else {
                        if (silentCurNumber === 0) {
                          clearInterval(_interval);
                          this.stopRecordAndProcess(stopTimeGap);
                          return;
                        }
                        silentCurNumber--;
                        this.livingbody.livingbodySilentText = silentCurNumber;
                      }
                    }, timeGap);
                  },
                  // startRecord fail
                  fail: err => {
                    console.log("err", err);
                    this.livingbody.isShowGuide = true;
                    this.livingbody.isShowCamera = false;
                    this.livingbody.isPrepare = false;
                    this.ctx = null;
                    console.log("start record fail", +new Date(), err);
                    this.showErrorToast({
                      ErrorCode: -108,
                      ErrorMsg: `网络异常，请重试${err.errMsg}`
                    });
                    clearInterval(_interval);
                  },
                  complete: res => {
                    console.log("complete", res);
                  }
                });
              },
              // if network exception
              err => {
                console.log("checkRecordNetworkOk", err);
                this.livingbody.isShowGuide = true;
                this.livingbody.isShowCamera = false;
                this.showErrorToast(err);
              }
            );
          }, 2000);
        });
      }, this.showErrorToast);
    },
    // checknet work return all
    returnAllCheckNetWork(callback) {
      uni.getNetworkType({
        success: function(res) {
          callback(res.networkType);
        },
        fail: function(e) {
          callback("none");
        }
      });
    },
    // upload the vieo
    uploadTheVideo(wx_req, size) {
      this.returnAllCheckNetWork(networkType => {
        // if not wifi
        if (networkType !== "wifi" && networkType !== "none") {
          // show warning and is continue
          uni.showModal({
            title: "提示",
            content: `视频大约${size}，在移动网络环境下上传会产生手机流量，确认继续？`,
            confirmText: "继续",
            confirmColor: "#2d72f1",
            success: res => {
              if (res.confirm) {
                this.uploadTheVideoMain(wx_req, size);
              } else {
                // do not, need back to guide
                this.livingbody.isShowGuide = true;
                this.livingbody.isShowCamera = false;
                this.livingbody.isShowProcess = false;
                this.isNotCamera = false;
                this.livingbody.isPrepare = true;
              }
            }
          });
        } else {
          this.uploadTheVideoMain(wx_req, size);
        }
      });
    },
    // livingbody stop record and process --- stoprecord,and go next
    stopRecordAndProcess(stopTimeGap) {
      console.log("start stopRecord", +new Date());
      setTimeout(() => {
        console.log("stopTimeGap" + stopTimeGap);
        this.ctx &&
          this.ctx.stopRecord({
            success: res => {
              console.log("stopRecord success", +new Date(), res);
              // check the network before upload the video
              uni.getFileInfo({
                filePath: res.tempVideoPath,
                success: resTemp => {
                  var sizek = Math.round(resTemp.size / 1024);
                  if (sizek > 30720) {
                    this.livingbody.isShowGuide = true;
                    this.livingbody.isShowCamera = false;
                    this.isNotCamera = true;
                    this.livingbody.isPrepare = true;
                    this.showErrorToast({
                      ErrorCode: -108,
                      ErrorMsg: `视频大小超过限制`
                    });
                  } else {
                    this.processTheVideo(res.tempVideoPath, sizek + "K");
                  }
                },
                fail: err => {
                  this.livingbody.isShowGuide = true;
                  this.livingbody.isShowCamera = false;
                  this.livingbody.isPrepare = true;
                  this.showErrorToast({
                    ErrorCode: -108,
                    ErrorMsg: `getFileInfo异常，${err.errMsg}`
                  });
                }
              });
            },
            fail: err => {
              this.livingbody.isShowGuide = true;
              this.livingbody.isShowCamera = false;
              this.livingbody.isPrepare = true;
              this.showErrorToast({
                ErrorCode: -108,
                ErrorMsg: `stopRecord异常，${err.errMsg}`
              });
            },
            complete(e) {
              console.log("complete", e);
            }
          });
      }, stopTimeGap);
    },
    // livingbody number, the number code must be ok
    theLivingBodyNumberMustBeOk() {
      console.log("theLivingBodyNumberMustBeOk");
      // 重新获取
      uni.showModal({
        title: "提示",
        content: "获取code失败，" + this.livingbody.getCodeErrMsg,
        showCancel: false,
        confirmText: "重新获取",
        confirmColor: "#2d72f1",
        success: res => {
          if (res.confirm) {
            // 重新获取
            console.log("开始重新获取");
            uni.showLoading({
              title: "重新获取中...",
              mask: true
            });
            $http(
              {
                url:
                  this.cmsConfig.livingbodyType === 1
                    ? `/api/liveness/actioncode?BizToken=${this.token}`
                    : `/api/liveness/lipcode?BizToken=${this.token}`,
                method: "POST",
                reTry: {
                  tryCount: 5
                }
              },
              res => {
                uni.hideLoading();
                console.log("theLivingBodyNumberMustBeOk", res);
                if (res.ErrorCode === 0) {
                  console.log("Got the LipCode：" + res.Data.LipCode);
                  console.log("Got the ActionCode:" + res.Data.ActionCode);
                  this.livingbodyAutoShowDialog();
                  if (this.cmsConfig.livingbodyType === 1) {
                    this.livingbody.isActionSeqNormal =
                      res.Data.ActionCode.join("") === "21";
                    this.livingbody.isNotPrepareOk = false;
                  } else {
                    this.livingbody.livingbodyNumber = res.Data.LipCode;
                    this.livingbody.isNotPrepareOk = false;
                  }
                } else {
                  // 如果出现 14(本次校验已完成) 15 (token过期)的错误，退出验证
                  if (tokenExceptionArr.includes(res.ErrorCode)) {
                    exitVerifyFail(res);
                    return;
                  }
                  this.livingbody.getCodeErrMsg = res.ErrorMsg;
                  this.theLivingBodyNumberMustBeOk();
                  reportError(Log.lipcodeErr, res);
                }
              }
            );
          }
        }
      });
    },
    // livingbody number auto show dialog when first enter
    livingbodyAutoShowDialog() {
      let isAlreadyShowVideoRule = uni.getStorageSync("isAlreadyShowVideoRule");
      // 如果有值，说明之前已经显示，有缓存，
      if (isAlreadyShowVideoRule) {
      } else {
        // 如果没有，说明第一次进入
        this.livingbody.isShowDialog = !this.livingbody.isShowDialog;
        uni.setStorage({
          key: "isAlreadyShowVideoRule",
          data: "true"
        });
      }
    },

    // livingbody process the video  -- goto next process page, and exception handle
    processTheVideo(tempVideoPath, size) {
      checkRecordNetworkOk(
        networkType => {
          this.goToProcessPage(tempVideoPath, size);
        },
        // network error
        err => {
          this.livingbody.isShowGuide = true;
          this.livingbody.isShowCamera = false;
          this.livingbody.isPrepare = true;
          // show warning and is continue
          uni.showModal({
            title: "提示",
            content: "网络异常，请检查网络后重试",
            confirmText: "重试",
            confirmColor: "#2d72f1",
            success: res => {
              if (res.confirm) {
                // 如果是重试，走process流程，
                this.processTheVideo(tempVideoPath, size);
              } else {
                // do not, need record again
              }
            }
          });
        }
      );
    },
    switchLivingbodyDialog(e) {
      this.livingbody.isShowDialog = !this.livingbody.isShowDialog;
    },
    goToProcessPage(tempVideoPath, size) {
      // return;
      this.livingbody.isShowGuide = false;
      this.livingbody.isShowCamera = false;
      this.livingbody.isShowProcess = true;
      this.isNotCamera = false;
      this.livingbody.isPrepare = true;
      // start upload
      let wx_req = {
        url: `${this.baseUrl}/api/common/upLoadWxAppFile?BizToken=${
          this.token
        }`,
        filePath: tempVideoPath,
        data: {
          file: tempVideoPath
        }
      };
      this.uploadTheVideo(wx_req, size);
    },
    uploadTheVideoMain(wx_req, size) {
      this.uploadFile.call(this, wx_req, res => {
        console.log("上传视频成功");
        console.log(res);
        if (res.ErrorCode === 0) {
          // upload success
          console.log("uploadSuccess");
          console.log(res.Data.Data.MediaKey);
          this.livingbodyVerify(res.Data.Data.MediaKey);
        } else {
          // need re-upload
          // show warning and is continue
          var msg = "网络异常，上传视频失败";
          if (res.ErrorCode !== 101) {
            msg = res.ErrorMsg;
          }
          uni.showModal({
            title: "提示",
            content: msg,
            showCancel: false,
            confirmText: "重试",
            confirmColor: "#2d72f1",
            success: res => {
              if (res.confirm) {
                // 如果是重试，走process流程，
                this.uploadTheVideo(wx_req, size);
              }
            }
          });
        }
      });
    },
    uploadFile(wx_req, callback) {
      // upload
      console.log(wx_req);
      let uploadTask = wx.uploadFile({
        url: wx_req.url,
        filePath: wx_req.filePath,
        name: "file",
        formData: wx_req.data,
        success: res => {
          console.log("uploadFile| ", res);
          if (res.statusCode === 200) {
            console.log(res);
            let resTemp = JSON.parse(res.data);
            console.log("resTemp");
            console.log(resTemp);
            if (resTemp.ErrorCode === 0) {
              // upload success
              console.log(this.data);
              callback({ ErrorCode: 0, Data: resTemp });
            } else {
              callback({
                ErrorCode: resTemp.ErrorCode,
                ErrorMsg: "上传视频失败，" + resTemp.ErrorMsg
              });
            }
          } else {
            callback({
              ErrorCode: 101,
              ErrorMsg: "上传视频失败 " + res.statusCode
            });
          }
        },
        fail: e => {
          console.log("upload img fail", e);
          callback({ ErrorCode: 101, ErrorMsg: "上传视频失败, " + e.errMsg });
        }
      });

      uploadTask.onProgressUpdate(res => {
        this.livingbody.uploadProcess =
          res.progress - 10 < 0 ? 0 : res.progress - 10;
        console.log("progress", res.progress);
        console.log("already upload data", res.totalBytesSent);
        console.log("all upload data", res.totalBytesExpectedToSend);
      });
    },
    // livingbody verify
    livingbodyVerify(MediaKey) {
      console.log("livingbodyVerify", MediaKey);
      // 是否是一次验证？ 活体类型是什么？通用的参数有哪些
      let livingbodyType = this.cmsConfig.livingbodyType;
      let url = "/api/liveness/lipliveness";
      if (livingbodyType === 1) {
        url = "/api/liveness/actionliveness";
      } else if (livingbodyType === 2) {
        url = "/api/liveness/silentliveness";
      }
      $http(
        {
          url: `${url}?BizToken=${this.token}`,
          data: {
            MediaKey: MediaKey
          },
          methods: "POST"
        },
        res => {
          console.log('livingbodyVerify res',res)
          if (res.ErrorCode === 0) {
            if (this.cmsConfig.page.success.isAutoSkip) {
              exitVerify({});
            } else {
              $common.setCurPage({
                url: "result",
                params: { type: "success" }
              });
            }
          } else if (res.ErrorCode === -107 || res.ErrorCode === 101) {
            // request异常 或 网络异常
            uni.showModal({
              title: "提示",
              content: res.error_msg,
              showCancel: false,
              confirmText: "重试",
              confirmColor: "#2d72f1",
              success: res => {
                if (res.confirm) {
                  // 如果是重试，走process流程，
                  this.livingbodyVerify(MediaKey);
                }
              }
            });
            reportError(Log.livingbodyVerifyErr, res, {
              apiUrl: `${this.baseUrl}${url}?BizToken=${this.token}`
            });
          } else if (tokenExceptionArr.includes(res.ErrorCode)) {
            // 如果出现 14(本次校验已完成) 15 (token过期)的错误，退出验证
            exitVerifyFail(res);
            reportError(Log.exitVerifyFail, res, {
              apiUrl: `${this.baseUrl}${url}?BizToken=${this.token}`
            });
          } else {
            // 606 身份证号码少一位也会这样  身份证照片信息拉取失败
            // 设置错误信息
            // 1. 先看error_code是否为undefined，如果是使用9999错误码, 返回403、503 html文本内容
            // 2. 先查询cms配置里是否有该错误码的配置，如果没有使用系统的错误码
            if (res.ErrorCode === undefined) {
              res.ErrorCode = "9999";
              sysFailInfo["9999"].tips1 = res.Data;
            }
            var ErrorCode = res.ErrorCode + "";
            var failInfo = {};
            // 如果cms配置里有值
            if (this.cmsConfig.failInfo && this.cmsConfig.failInfo[ErrorCode]) {
              failInfo = this.cmsConfig.failInfo[ErrorCode];
            } else if (sysFailInfo[ErrorCode]) {
              // 使用系统默认错误
              failInfo = sysFailInfo[ErrorCode];
            } else {
              // 使用后台返回的错误信息
              failInfo = {
                img: "",
                msg: res.ErrorMsg,
                error_code: res.ErrorCode
              };
            }
            failInfo.Data = res.Data || {};
            this.failInfo = failInfo;
            console.log('result',res)
            $common.setCurPage({
                url: "result",
                params: { type: "fail",
                info: failInfo }
            });
            reportError(Log.livingbodyVerifyErr, res, {
              apiUrl: `${this.baseUrl}${url}?BizToken=${this.token}`
            });
          }
        }
      );
    },
    showErrorToast(err) {
      console.log("showErrorToast err=>", err);
      this.showErrorMsg = true;
      this.err = err;
    },
    // 活体摄像头非正常中止
    bindstop(e) {
      console.log("errorcamera", e);
    },
    ocrCameraError(e) {
      console.log("ocrCameraError", e);
    }
  }
};
</script>

<style scoped>
#livingbody-guide-title {
  width: 100%;
  margin: 50rpx 0 60rpx;
  text-align: center;
  font-size: 35rpx;
}

.livingbody-guide-imgview {
  width: 100%;
  margin-bottom: 50rpx;
  text-align: center;
}

.livingbody-guide-imgview image {
  width: 398rpx;
  height: 560rpx;
}

#livingbody-guide-btnview {
  width: 100%;
  margin: 0 auto;
}

#livingbody-guide-btnview button {
  margin: 30rpx 30rpx 10rpx 30rpx;
}

#livingbody-guide-showdialog {
  width: 100%;
  margin-top: 26rpx;
  text-align: center;
  font-size: 14px;
  color: #007fff;
}

#livingbody-dialog-main {
  max-width: 1000rpx;
  background: none;
}

#livingbody-dialog-title {
  margin-bottom: 15px;
  padding: 15rpx 0;
  color: #fff;
}

#livingbody-dialog-bg {
  display: block;
  padding: 0 auto;
}

#livingbody-dialog-bg image {
  width: 561rpx;
  height: 753rpx;
}

#livingbody-dialog-bg button {
  width: 555rpx;
  margin: 25px auto;
  font-size: 18px;
  border-color: #fff;
  color: #fff;
}

/* 
 * pu gai, cover-view exec width animation just run in devtools is ok, the real machine debugging is invaild 
 * read number show every number process function already pu gai, wait wechat support this in the future 
 */
/* #test {
  animation: upAndDown 4s linear infinite;
}
@keyframes upAndDown {
    0% {width:0;}
    100% {width:180px;}
} */

.lvingbody-number-text {
  display: inline-block;
  width: 120rpx;
  line-height: 1em;
  color: white;
}

.livingbody-number-hint {
  position: absolute;
  bottom: 550rpx;
  display: inline-block;
  width: 100%;
  line-height: 1em;
  text-align: center;
  font-size: 120rpx;
  color: #2574ea;
}
.isInfinityDisplayHTNumberHint {
  bottom: 750rpx;
}
.livingbody-action-hint {
  position: absolute;
  bottom: 580rpx;
  display: inline-block;
  height: 92rpx;
  width: 100%;
  line-height: 1em;
  text-align: center;
  font-size: 92rpx;
  color: #2574ea;
  z-index: 100;
}
.isInfinityDisplayHTActionHint {
  bottom: 780rpx;
}
.livingbody-number-pre {
  position: absolute;
  bottom: 535rpx;
  width: 100%;
  font-size: 92rpx;
  text-align: center;
  color: #2574ea;
  z-index: 100;
}
.isInfinityDisplayHTNumberPre {
  bottom: 735rpx;
}

.livingbody-action-pre {
  position: absolute;
  bottom: 550rpx;
  width: 100%;
  font-size: 92rpx;
  text-align: center;
  color: #2574ea;
  z-index: 100;
}
.isInfinityDisplayHTActionPre {
  bottom: 750rpx;
}

.livingbody-bg {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 960rpx;
  z-index: 100;
}

.isInfinityDisplayHTBottom {
  bottom: 200rpx;
}

.livingbody-title {
  position: absolute;
  top: 0;
  bottom: 955rpx;
  left: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 52rpx;
  color: #2574ea;
  background: #fff;
  z-index: 100;
}

.isInfinityDisplayHTTitle {
  bottom: 1155rpx;
}

.livingbody-camera {
  position: fixed;
  top: 0;
  bottom: 0;
  width: 100%;
}

.livingbody-silent {
  position: absolute;
  bottom: 40rpx;
  width: 100%;
  text-align: center;
  z-index: 100;
}

.livingbody-silent-view {
  display: flex;
  align-items: center;
  width: 122px;
  height: 36px;
  margin: 0 auto;
  font-size: 22px;
  border-radius: 50px;
  color: white;
  background: rgba(0, 0, 0, 0.5);
}

.livingbody-silent-hintone {
  display: flex;
  align-items: center;
  margin: 0 2px 0 22px;
  letter-spacing: 1px;
  font-size: 19px;
}

.livingbody-silent-hinttwo {
  display: flex;
  align-items: center;
  margin-left: 2px;
}

.livingbody-silent-prepare {
  display: flex;
  align-items: center;
  margin-left: 16px;
}

.verifyCurrentNumber {
  color: #2574ea;
}

#livingbody-process .scan {
  position: relative;
  width: 210rpx;
  height: 250rpx;
  margin: 160rpx auto 150rpx;
}

#livingbody-process .scan image {
  width: 210rpx;
  height: 250rpx;
}

#livingbody-process-m {
  width: 100%;
}

#livingbody-process-m progress {
  margin: 0 auto;
  width: 450rpx;
  border: 1px solid #fff;
  border-radius: 10px;
}

#livingbody-process-title {
  width: 100%;
  margin-top: 40rpx;
  text-align: center;
  font-size: 34rpx;
}

.livingbody-risk-tip {
  margin: 20rpx 30rpx;
}
.weui-mask {
  position: fixed;
  z-index: 1000;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
}

.weui-dialog {
  position: fixed;
  z-index: 5000;
  width: 75%;
  max-width: 300px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background-color: #ffffff;
  text-align: center;
  overflow: inherit;
  border-radius: 5px;
}

.weui-dialog .weui-icon_area {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0;
}

.weui-dialog__hd {
  padding: 1.3em 1.6em 0.5em;
  padding-top: 50px;
  margin-bottom: 20px;
  line-height: inherit;
}

.weui-dialog__ft {
  position: relative;
  line-height: 48px;
  font-size: 18px;
  border-top: 0.5px solid #ccc;
}

.weui-dialog__btn_primary {
  color: #2d72f1;
}

.weui-dialog .weui-icon_area .iconbg {
  position: absolute;
  top: 10rpx;
  bottom: 10rpx;
  left: 10rpx;
  right: 10rpx;
  background: #fff;
  border-radius: 100%;
}

.weui-dialog.style2 .weui-icon_area .icon-box-img {
  position: relative;
}

.weui-dialog__title {
  font-weight: 400;
  font-size: 18px;
}
.index-btn {
  margin: 30rpx 30rpx 10rpx 30rpx;
}

.index-btn button {
  background-color: #2d72f1;
  color: white;
}
.index-btn button[disabled] {
  background: #b3b3b3 !important;
  color: rgba(255, 255, 255, 0.6) !important;
}

.index-btnNative {
  margin: 30rpx 30rpx 10rpx 30rpx;
}

.index-btnNative button {
  /* background-color:#2d72f1; */
  color: white;
}

.index-btnNative button[disabled] {
  color: rgba(255, 255, 255, 0.6) !important;
}

.index-btnNative button[disabled][type="primary"] {
  background-color: #9ed99d !important;
}
</style>
